/**
 * 
 */
package com.agilegroup.crm.ui.fragments;

import static com.agilegroup.crm.utils.CONSTANTS.ADD_CALL_CALENDAR;
import static com.agilegroup.crm.utils.CONSTANTS.callsURL;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.CallAdapter;
import com.agilegroup.crm.model.Calendar;
import com.agilegroup.crm.model.CalendarData;
import com.agilegroup.crm.model.CallData;
import com.agilegroup.crm.model.CallList;
import com.agilegroup.crm.requests.CalendarJsonRequest;
import com.agilegroup.crm.requests.CallsJsonRequest;
import com.agilegroup.crm.ui.ViewCallActivity;
import com.agilegroup.crm.utils.CalendarSync;
import com.agilegroup.crm.utils.OnlineChecker;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class CallFragment extends SherlockListFragment{
	 
		private static final String JSON_CACHE_KEY = "calls_json";
		private OnlineChecker checker;
		
	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	        return super.onCreateView(inflater, container, savedInstanceState);
	    }
		@Override
	    public void onCreate(Bundle savedInstanceState) {
		    // TODO Auto-generated method stub
		    super.onCreate(savedInstanceState);
		    setRetainInstance(true);
		    setHasOptionsMenu(true);
		    checker = new OnlineChecker(getActivity());
		    
		    Intent intent = getSherlockActivity().getIntent();
		    String leadId = intent.getStringExtra("leadId");
	        Log.d("leaId", leadId);
	        
		   	AgileApplication.getInstance().spiceManager.execute(new CallsJsonRequest(leadId,callsURL),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new CallListJsonRequestListener());
//		   	callsTask = new CallFromServer(this);
//		   	callsTask.execute(empId);
	    }
	    public class CallListJsonRequestListener implements RequestListener<CallList>{

			public void onRequestFailure(SpiceException spiceException) {
				Toast.makeText(CallFragment.this.getSherlockActivity(), "Failure", Toast.LENGTH_SHORT).show();
				getListView().clearAnimation();
			}

			public void onRequestSuccess(CallList result) {
				List<CallData>callData = result.getCallData();
				if (callData.size()==0) {
					setEmptyText(getResources().getString(R.string.no_data));
				}
				CallAdapter adapter = new CallAdapter(getSherlockActivity(), callData);
				setListAdapter(adapter);
			}

		 }
	    @Override
	    public void onListItemClick(ListView l, View v, int position, long id) {
	    	TextView accountId = (TextView)v.findViewById(R.id.txtid);
	    	if(checker.isOnline()==true){
	    		Intent view = new Intent(CallFragment.this.getSherlockActivity(),ViewCallActivity.class);
	    		view.putExtra("callId", accountId.getText().toString());
	    		CallFragment.this.getSherlockActivity().startActivity(view);
	    	}
	    	else{
	    		SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
    			dialogFragment.show(getSherlockActivity().getSupportFragmentManager(), "connectionDialog");
	    	}
	    	
	    }
	    
	    @Override
		public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			inflater.inflate(R.menu.calls_menu, menu);
			super.onCreateOptionsMenu(menu, inflater);
		}
	    
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent intent = getSherlockActivity().getIntent();
			String leadId = intent.getStringExtra("leadId");
			switch (item.getItemId()) {
			case R.id.action_refresh_calls:		
					AgileApplication.getInstance().spiceManager.execute(new CallsJsonRequest(leadId,callsURL),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new CallListJsonRequestListener());
				break;
			case R.id.action_sync_calls:
				AgileApplication.getInstance().spiceManager.execute(new CalendarJsonRequest("call",leadId,ADD_CALL_CALENDAR),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new CallCalendarJsonRequestListener());
				break;
			case android.R.id.home:
				getActivity().finish();
			break;
			default:
				break;
			}
			return super.onOptionsItemSelected(item);
		}
		public class CallCalendarJsonRequestListener implements RequestListener<CalendarData>{

			@Override
			public void onRequestFailure(SpiceException spiceException) {
				Toast.makeText(CallFragment.this.getSherlockActivity(), "Failure", Toast.LENGTH_SHORT).show();	
			}

			@Override
			public void onRequestSuccess(CalendarData result) {
				Log.d(CallCalendarJsonRequestListener.class.getSimpleName(), "success");
				List<Calendar>calendars = result.getCalendars();
				if(calendars==null){
					Toast.makeText(getSherlockActivity(), "There's no call to sync", Toast.LENGTH_SHORT).show();
				}
				else{
					
					CalendarSync sync = new CalendarSync(getSherlockActivity(),2);
					sync.createEvents(calendars);
				}
			}
			
		}
	}